package com.ruoyi.web.controller.shopping.collect;

import com.ruoyi.system.domain.Collect;
import com.ruoyi.system.domain.CollectDto;
import com.ruoyi.system.domain.Product;
import com.ruoyi.system.service.CollectService;
import com.ruoyi.system.service.ProductService;
import com.ruoyi.system.view.common.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/xiaomi/v2/collect")
public class CollectController {
    @Autowired
    private ProductService productService;

    @Autowired
    private CollectService collectService;

    @PostMapping("/{productId}")
    public R<String> toCollect(@PathVariable(value = "productId") Integer productId, HttpServletRequest request){
        String user_id = null;
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if(cookie.getName().equals("token")){
                System.out.println(cookie.getValue());
                user_id = cookie.getValue();
            }
        }
        List<CollectDto> collect = collectService.getCollect(Integer.valueOf(user_id),productId);
        if(collect.size() != 0){
            //已经被当前用户收藏，移出收藏
            collectService.deleteCollect(Integer.valueOf(user_id),productId);
            return R.success("取消收藏");
        }
        //未被当前用户收藏,开始收藏
        Collect collect1 = new Collect();
        collect1.setUser_id(Integer.valueOf(user_id));
        collect1.setProduct_id(productId);
//        时间随便存一个了，有问题后面再搞
        collect1.setCollect_time(productId);
        collectService.insertCollect(collect1);
        return R.success("收藏成功");
    }

    @GetMapping
    public R<List<CollectDto>> getCollect(HttpServletRequest request){
        String user_id = null;
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if(cookie.getName().equals("token")){
                System.out.println(cookie.getValue());
                user_id = cookie.getValue();
            }
        }
        List<CollectDto> collect = collectService.getCollect(Integer.valueOf(user_id),null);
        for (CollectDto collectDto : collect) {
            System.out.println(collectDto);
            Product all = productService.getAll(null, collectDto.getProductId(), null);
            collectDto.setProductId(all.getProductId());
            collectDto.setProductName(all.getProductName());
            collectDto.setProductPicture(all.getProductPicture());
            collectDto.setProductPrice(all.getProductPrice());
            collectDto.setProductSellingPrice(all.getProductSellingPrice());
            collectDto.setProductTitle(all.getProductTitle());
        }
        return R.success(collect);
    }
}
